#include "xftp_server_cmd.hpp"
#include "events_buffer_cb.hpp"
#include "events_cb.hpp"

#include <glog/logging.h>
#include <event2/bufferevent.h>
#include <event2/event.h>

#include <string>

xftp_server_cmd::xftp_server_cmd(/* args */)
{
    base = NULL;
}

xftp_server_cmd::~xftp_server_cmd()
{
        
}
void xftp_server_cmd::read_cb(struct bufferevent *buffer)
{
    char data[1024] ={0};
    VLOG(0)<<"xftp_server_cmd::read_cb data"; 
    for(;;)
    {
        int len = bufferevent_read(buffer,data,sizeof(data)-1);
        if (len<=0)
        {
            /* code */
            break;
        }
        std::string type = "";
        for (size_t i = 0; i < len; ++i)
        {
            if(data[i]== ' '||data[i]=='\r')
            break;
            type +=data[i];
        }
        VLOG(0)<<"type = "<<type;
        
        if(m_call_task.find(type) != m_call_task.end())
        {
            xftp_task *t =m_call_task[type];
            // t->recv_bffer = buffer; // 将文件描述符移交出去
            t->m_cmd_task = this;       // 用来处理回复命令和目录路径的，相当于移交了文件描述符
            
            t->ip = ip;
            t->port = port;
            t->base = base;
            t->parse_cmd(type,data);
            if(type == "PORT")
            {
                ip = t->ip;
                port = t->port;
            }
        }
        else
        {
            std::string msg = "200 OK\r\n";
            VLOG(0)<<"recv msg = "<<msg;
            bufferevent_write(buffer,msg.c_str(),msg.size());
        }
        VLOG(0)<<"recv client cmd = "<<data;
        // 将任务分发到处理对象中去
    }
}
void xftp_server_cmd::event_cb(struct bufferevent *buffer,short what)
{
  if (what &(BEV_EVENT_EOF|BEV_EVENT_ERROR|BEV_EVENT_TIMEOUT))
    {
        /* code */
        VLOG(0)<<"buffevent quit | buffevent | timeout error";
        bufferevent_free(buffer);
        delete this;
    }
}
void xftp_server_cmd::registration_command(std::string cmd,xftp_task* call_task)
{
    if(!call_task)
    {
        VLOG(3)<<"xftp_server_cmd reg call error";
        return;
    }
    if(cmd.empty())
    {
        VLOG(3)<<"xftp-server_cmd cmd is error";
        return;
    }
    if(m_call_task.find(cmd) != m_call_task.end())
    {
        // 已经注册的命令提示错误
        VLOG(3)<<"xftp_server cmd is register";
        return;
    }
    m_call_task[cmd] = call_task;

    // 注册事件
}

bool xftp_server_cmd::Init()
{
    VLOG(1)<<"xftp_server_cmd_init()"<<std::endl;
    
    bufferevent *buffer = bufferevent_socket_new(base,sockfd,BEV_OPT_CLOSE_ON_FREE); // 关闭关闭socket对象
    this->recv_bffer = buffer;
    /*
    bufferevent_setcb(buffer,events_cb::read_cb,0,events_cb::event_cb,this);
    bufferevent_enable(buffer,EV_READ|EV_WRITE);
    */
    
    this->set_event_callback(buffer);
    timeval recv_time={60,0};
    bufferevent_set_timeouts(buffer,&recv_time,NULL);
    // 设置缓冲区事件权限
    std::string msg = "220 wlcome to libevent xftp_server_cmd \r\n";
    bufferevent_write(buffer,msg.c_str(),msg.size());

    return true;
}
